#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os,sys
import json
import time
import threading
from http.server import HTTPServer, BaseHTTPRequestHandler
import ocrUtil
import cv2
import base64
import numpy as np
ocrtool = ocrUtil.OCRObj()

isORC = False

class TestHTTPHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        print(self.path)
        print(self.client_address)
        try:
            # fpth = '/root/svnclient/svnp8100/httpserver' + self.path
            fpth = '.' + self.path
            if os.path.exists(fpth):
                f = open(fpth,'r')
                jstr = f.read()
                f.close()
                self.sendJsonMsg(jstr)
                return None
            elif self.path == '':
                self.send_error(404,'File Not Found: %s' % self.path) 
                return None
        except Exception as e:
            print(e)
            self.send_error(404,'File Not Found: %s' % self.path)  
            return None
        
    def sendJsonMsg(self,jmsg):
        length = len(jmsg)
        print('length=%d'%(length))
        self.send_response(200)
        self.send_header("Content-type", "application/octet-stream")
        self.send_header("Content-Length", str(length))
        self.end_headers()
        self.wfile.write(jmsg.encode())
    def do_POST(self):
        global ocrtool
        global isORC
        try:
            if isORC:
                outjstr = json.dumps({'erro':1,'data':None},ensure_ascii=False)
                print(outjstr)
                self.sendJsonMsg(outjstr)
                return
            isORC = True
            # dictmp = self.do_GET()
            print(self.path)
            print(self.path.encode())
            print(type(self.path))
            print(self.client_address)
            #获取post提交的数据
            jpg_as_str = self.rfile.read(int(self.headers['content-length']))    #固定格式，获取表单提交的数据
            jpg_as_str=json.loads(jpg_as_str)['img_str']
            jpg_as_bytes = jpg_as_str.encode('ascii')
            jpg_original = base64.b64decode(jpg_as_bytes)
            jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8)
            imgtmp = cv2.imdecode(jpg_as_np, flags=1)
            out = ocrtool.ocrImg(imgtmp)
            outjstr = json.dumps({'erro':0,'data':out})
            print(outjstr)
            self.sendJsonMsg(outjstr)
            isORC = False
        except:
            print('orc erro')
            isORC = False
        print('do post')
        
        
    # def do_HEAD(self):
    #     """Serve a HEAD request."""
    #     f = self.send_head()
    #     if f:
    #         f.close()

def runHttpServer(ip,port):
    http_server = HTTPServer((ip, int(port)), TestHTTPHandler)
    print('server is start:(%s,%d)'%(ip,port))
    http_server.serve_forever() #设置一直监听并接收请求

def getIPAndPort():
    f = open('ocrConfig.txt','r')
    dtmp = f.read()
    f.close()
    dictmp = json.loads(dtmp)
    return dictmp['ip'],dictmp['port']

def start_server():
    ip,port = getIPAndPort()
    thr = threading.Thread(target=runHttpServer,args=(ip,port))
    thr.setDaemon(True)
    thr.start()

def main():
    start_server()
    while True:
        time.sleep(1000)

if __name__ == '__main__':
    main()
